import React, { useState, useEffect } from 'react';
import { Link, useNavigate, useLocation } from 'react-router-dom';
import AIChatWidget from './AIChat';
import './MainLayout.css';
import ptLogo from '../assets/pt-logo.png';

const MainLayout = ({ children }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const [userData, setUserData] = useState(null);

  useEffect(() => {
    // 从本地存储获取用户信息
    const userInfo = localStorage.getItem('user');
    if (userInfo) {
      setUserData(JSON.parse(userInfo));
    } else {
      // 如果没有用户信息，且当前不在登录相关页面，则跳转到登录页
      const authPaths = ['/login', '/register', '/forgot-password'];
      if (!authPaths.includes(location.pathname)) {
        navigate('/login');
      }
    }
  }, [location.pathname, navigate]);

  const handleLogout = () => {
    localStorage.removeItem('token');
    localStorage.removeItem('user');
    navigate('/login');
  };

  // 检查是否应该显示AI聊天组件（只在用户已登录时显示）
  const shouldShowAIChat = userData && !location.pathname.includes('/login') && !location.pathname.includes('/register');

  return (
    <div className="main-layout">
      {/* 顶部导航栏 */}
      <header className="main-header">
        <div className="header-content">
          <div className="header-logo">
            <Link to="/">
              <img src={ptLogo} alt="PT种子站" className="logo-image" />
              <span className="logo-text">PT种子站</span>
            </Link>
          </div>

          <nav className="main-nav">
            <ul className="nav-links">
              <li className={location.pathname.includes('/categories') || location.pathname === '/' ? 'active' : ''}>
                <Link to="/categories">资源</Link>
              </li>
              <li className={location.pathname.includes('/network') ? 'active' : ''}>
                <Link to="/network">局域网</Link>
              </li>
              <li className={location.pathname.includes('/points') ? 'active' : ''}>
                <Link to="/points">积分系统</Link>
              </li>
              <li className={location.pathname.includes('/help') ? 'active' : ''}>
                <Link to="/help">帮助中心</Link>
              </li>
            </ul>
          </nav>

          {userData ? (
            <div className="user-section">
              <div className="user-dropdown">
                <div className="user-info">
                  <img src={userData.avatarUrl} alt="用户头像" className="user-avatar" />
                </div>
                <div className="dropdown-menu">
                  <Link to="/user/profile" className="dropdown-item">
                    <i className="icon-user"></i> 个人资料
                  </Link>
                  <Link to="/user/passkey" className="dropdown-item">
                    <i className="icon-key"></i> Passkey管理
                  </Link>
                  <Link to="/user/invitation-history" className="dropdown-item">
                    <i className="icon-invitation"></i> 邀请记录
                  </Link>
                  <Link to="/user/myDownload" className="dropdown-item">
                    <i><span className="stat-icon">⬇️ </span></i> 我的下载
                  </Link>
                  <Link to="/user/upload" className="dropdown-item">
                    <i><span className="stat-icon">⬆️ </span></i> 上传管理
                  </Link>
                  <div className="dropdown-divider"></div>
                  <button onClick={handleLogout} className="dropdown-item logout-item">
                    <i className="icon-logout"></i> 退出登录
                  </button>
                </div>
              </div>
            </div>
          ) : (
            <div className="auth-links">
              <Link to="/login" className="auth-btn login-btn">登录</Link>
              <Link to="/register" className="auth-btn register-btn">注册</Link>
            </div>
          )}
        </div>
      </header>

      {/* 内容区域 */}
      <main className="main-content">
        {children}
      </main>

      {/* 页脚 */}
      <footer className="main-footer">
        <div className="footer-content">
          <p>© 2025 PT种子站 - 版权所有</p>
        </div>
      </footer>

      {/* AI聊天组件 - 只在用户登录时显示 */}
      {shouldShowAIChat && <AIChatWidget />}
    </div>
  );
};

export default MainLayout;